<template>
  <view class="agreement-container">
    <!-- 状态卡片 -->
    <view class="status-card">
      <view class="status-icon-wrapper">
        <view v-if="agreementStatus === 'signed'" class="status-icon success">
          <uni-icons type="checkmarkempty" size="40" color="#52c41a"></uni-icons>
        </view>
        <view v-else-if="agreementStatus === 'pending'" class="status-icon warning">
          <uni-icons type="info" size="40" color="#faad14"></uni-icons>
        </view>
        <view v-else class="status-icon default">
          <uni-icons type="closeempty" size="40" color="#999"></uni-icons>
        </view>
      </view>
      <view class="status-info">
        <text class="status-title">{{ statusTitle }}</text>
        <text class="status-desc">{{ statusDesc }}</text>
        <text v-if="signTime" class="sign-time">签订时间：{{ signTime }}</text>
      </view>
    </view>

    <!-- 承诺书内容 -->
    <view class="content-card">
      <view class="content-header">
        <text class="content-title">食品安全质量承诺书</text>
      </view>
      
      <view class="content-body">
        <view class="section">
          <text class="section-text">
            为确保食品安全，保障消费者身体健康和生命安全，本商户郑重承诺：
          </text>
        </view>

        <view class="section">
          <text class="section-title">一、严格遵守法律法规</text>
          <text class="section-text">
            严格遵守《中华人民共和国食品安全法》《中华人民共和国农产品质量安全法》等相关法律法规，依法经营，诚信经营。
          </text>
        </view>

        <view class="section">
          <text class="section-title">二、建立进货查验制度</text>
          <text class="section-text">
            1. 建立并执行进货查验记录制度，查验供货商的资质证明、产品合格证明等相关文件。
            2. 如实记录产品名称、规格、数量、供货商名称及联系方式、进货日期等内容。
            3. 进货查验记录保存期限不少于产品保质期满后六个月。
          </text>
        </view>

        <view class="section">
          <text class="section-title">三、保证产品质量安全</text>
          <text class="section-text">
            1. 不销售不符合食品安全标准的食品。
            2. 不销售病死、毒死或者死因不明的禽、畜、兽、水产动物肉类及其制品。
            3. 不销售未按规定进行检疫或者检疫不合格的肉类及其制品。
            4. 不销售使用国家禁止的农药、兽药或者其他化学物质的产品。
            5. 不销售农药、兽药等化学物质残留超过食品安全标准限量的产品。
          </text>
        </view>

        <view class="section">
          <text class="section-title">四、配合监督检查</text>
          <text class="section-text">
            1. 主动接受市场开办方的管理和监督检查。
            2. 配合相关部门进行食品安全监督抽检。
            3. 发现食品安全问题，立即停止销售，及时报告并配合调查处理。
          </text>
        </view>

        <view class="section">
          <text class="section-title">五、承担法律责任</text>
          <text class="section-text">
            如违反上述承诺，愿意承担相应的法律责任，并接受相关部门的处理。
          </text>
        </view>

        <view class="section signature-section">
          <view class="signature-info">
            <text class="signature-label">承诺商户：</text>
            <text class="signature-value">{{ merchantName }}</text>
          </view>
          <view class="signature-info">
            <text class="signature-label">法人代表：</text>
            <text class="signature-value">{{ legalPerson }}</text>
          </view>
          <view class="signature-info">
            <text class="signature-label">联系电话：</text>
            <text class="signature-value">{{ contactPhone }}</text>
          </view>
          <view v-if="signTime" class="signature-info">
            <text class="signature-label">签订日期：</text>
            <text class="signature-value">{{ signDate }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button v-if="agreementStatus === 'unsigned'" 
              class="action-btn sign-btn" 
              @click="handleSign">
        <uni-icons type="compose" size="20" color="#fff"></uni-icons>
        <text class="btn-text">立即签订</text>
      </button>
      
      <button class="action-btn download-btn" @click="handleDownload">
        <uni-icons type="download" size="20" color="#1890ff"></uni-icons>
        <text class="btn-text">下载PDF</text>
      </button>
      
      <button v-if="agreementStatus === 'signed'" 
              class="action-btn view-btn" 
              @click="handleViewPDF">
        <uni-icons type="eye" size="20" color="#52c41a"></uni-icons>
        <text class="btn-text">查看原件</text>
      </button>
    </view>

    <!-- 签订确认弹窗 -->
    <uni-popup ref="signPopup" type="center">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">确认签订承诺书</text>
        </view>
        <view class="popup-body">
          <text class="popup-text">
            请确认您已仔细阅读并理解《食品安全质量承诺书》的全部内容。
          </text>
          <text class="popup-text">
            签订后，您将承担相应的法律责任和义务。
          </text>
        </view>
        <view class="popup-footer">
          <button class="popup-btn cancel" @click="closeSignPopup">取消</button>
          <button class="popup-btn confirm" @click="confirmSign">确认签订</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 承诺书状态: unsigned-未签订, pending-审核中, signed-已签订
      agreementStatus: 'unsigned',
      // 商户信息
      merchantName: '',
      legalPerson: '',
      contactPhone: '',
      // 签订信息
      signTime: '',
      signDate: '',
      // PDF文件路径
      pdfUrl: ''
    }
  },
  computed: {
    statusTitle() {
      const titles = {
        'unsigned': '未签订',
        'pending': '审核中',
        'signed': '已签订'
      }
      return titles[this.agreementStatus] || '未签订'
    },
    statusDesc() {
      const descs = {
        'unsigned': '请仔细阅读承诺书内容并签订',
        'pending': '承诺书正在审核中，请耐心等待',
        'signed': '您已签订质量安全承诺书'
      }
      return descs[this.agreementStatus] || ''
    }
  },
  onLoad() {
    this.loadAgreementInfo()
    this.loadMerchantInfo()
  },
  methods: {
    // 加载承诺书信息
    loadAgreementInfo() {
      // TODO: 调用API获取承诺书签订状态
      // 模拟数据
      this.agreementStatus = 'unsigned' // 可以是 'unsigned', 'pending', 'signed'
      if (this.agreementStatus === 'signed') {
        this.signTime = '2025-08-21 10:30:00'
        this.signDate = '2025年8月21日'
      }
    },
    
    // 加载商户信息
    loadMerchantInfo() {
      // 从用户信息中获取
      const userInfo = this.$store.state.user.userInfo || {}
      this.merchantName = userInfo.merchantName || '安阳市农贸市场商户'
      this.legalPerson = userInfo.realName || userInfo.nickName || '张三'
      this.contactPhone = userInfo.phonenumber || '138****8888'
    },
    
    // 处理签订
    handleSign() {
      this.$refs.signPopup.open()
    },
    
    // 关闭签订弹窗
    closeSignPopup() {
      this.$refs.signPopup.close()
    },
    
    // 确认签订
    async confirmSign() {
      this.$refs.signPopup.close()
      
      uni.showLoading({
        title: '签订中...'
      })
      
      try {
        // TODO: 调用API提交签订请求
        // const res = await signAgreement({
        //   merchantId: this.merchantId,
        //   type: 'safety_agreement'
        // })
        
        // 模拟签订成功
        setTimeout(() => {
          uni.hideLoading()
          this.agreementStatus = 'pending'
          uni.showToast({
            title: '签订成功，等待审核',
            icon: 'success'
          })
          
          // 更新签订时间
          const now = new Date()
          this.signTime = this.formatDateTime(now)
          this.signDate = this.formatDate(now)
        }, 1500)
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '签订失败',
          icon: 'none'
        })
      }
    },
    
    // 下载PDF
    handleDownload() {
      uni.showLoading({
        title: '准备下载...'
      })
      
      // TODO: 实际项目中应该从服务器获取PDF文件URL
      const pdfUrl = '/static/files/safety_agreement.pdf'
      
      // #ifdef H5
      // H5平台直接打开链接下载
      window.open(pdfUrl)
      uni.hideLoading()
      // #endif
      
      // #ifdef MP-WEIXIN
      // 微信小程序下载文件
      uni.downloadFile({
        url: this.$baseUrl + pdfUrl,
        success: (res) => {
          uni.hideLoading()
          if (res.statusCode === 200) {
            // 保存文件到本地
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: (saveRes) => {
                uni.showModal({
                  title: '下载成功',
                  content: '文件已保存到本地',
                  showCancel: false
                })
              },
              fail: () => {
                // 如果保存失败，直接打开预览
                uni.openDocument({
                  filePath: res.tempFilePath,
                  fileType: 'pdf',
                  showMenu: true
                })
              }
            })
          }
        },
        fail: () => {
          uni.hideLoading()
          uni.showToast({
            title: '下载失败',
            icon: 'none'
          })
        }
      })
      // #endif
      
      // #ifdef APP-PLUS
      // APP平台下载处理
      const downloader = plus.downloader.createDownload(
        this.$baseUrl + pdfUrl,
        {},
        (download, status) => {
          uni.hideLoading()
          if (status === 200) {
            plus.runtime.openFile(download.filename)
          } else {
            uni.showToast({
              title: '下载失败',
              icon: 'none'
            })
          }
        }
      )
      downloader.start()
      // #endif
    },
    
    // 查看PDF原件
    handleViewPDF() {
      // TODO: 实际项目中应该从服务器获取已签名的PDF文件URL
      const signedPdfUrl = '/static/files/signed_safety_agreement.pdf'
      
      // #ifdef H5
      window.open(signedPdfUrl)
      // #endif
      
      // #ifdef MP-WEIXIN
      uni.downloadFile({
        url: this.$baseUrl + signedPdfUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.openDocument({
              filePath: res.tempFilePath,
              fileType: 'pdf',
              showMenu: true
            })
          }
        },
        fail: () => {
          uni.showToast({
            title: '打开失败',
            icon: 'none'
          })
        }
      })
      // #endif
    },
    
    // 格式化日期时间
    formatDateTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      const second = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${year}年${month}月${day}日`
    }
  }
}
</script>

<style lang="scss" scoped>
.agreement-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #E8F5E9 0%, #F1F8E9 100%);
  padding-bottom: 120rpx;
  padding-top: 20rpx;
}

/* 状态卡片 */
.status-card {
  margin: 20rpx 30rpx 30rpx 30rpx;
  padding: 40rpx;
  background: white;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.1);
  
  .status-icon-wrapper {
    margin-right: 30rpx;
  }
  
  .status-icon {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    
    &.success {
      background: #f6ffed;
      border: 2rpx solid #b7eb8f;
    }
    
    &.warning {
      background: #fffbe6;
      border: 2rpx solid #ffe58f;
    }
    
    &.default {
      background: #f5f5f5;
      border: 2rpx solid #d9d9d9;
    }
  }
  
  .status-info {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  
  .status-title {
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .status-desc {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 10rpx;
  }
  
  .sign-time {
    font-size: 24rpx;
    color: #999;
  }
}

/* 承诺书内容 */
.content-card {
  margin: 30rpx;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.1);
  
  .content-header {
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    background: linear-gradient(135deg, #E8F5E9 0%, #F1F8E9 100%);
  }
  
  .content-title {
    font-size: 36rpx;
    font-weight: 500;
    color: #2E7D32;
    text-align: center;
    display: block;
  }
  
  .content-body {
    padding: 30rpx;
  }
  
  .section {
    margin-bottom: 30rpx;
    
    .section-title {
      display: block;
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 15rpx;
    }
    
    .section-text {
      display: block;
      font-size: 28rpx;
      color: #666;
      line-height: 1.8;
      text-align: justify;
      white-space: pre-wrap;
    }
  }
  
  .signature-section {
    margin-top: 40rpx;
    padding-top: 30rpx;
    border-top: 1rpx dashed #e0e0e0;
    
    .signature-info {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      
      .signature-label {
        font-size: 28rpx;
        color: #999;
        width: 160rpx;
      }
      
      .signature-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
}

/* 操作按钮 */
.action-buttons {
  padding: 30rpx;
  display: flex;
  gap: 20rpx;
  
  .action-btn {
    flex: 1;
    height: 88rpx;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    border: none;
    transition: all 0.3s;
    
    .btn-text {
      margin-left: 10rpx;
    }
    
    &.sign-btn {
      background: linear-gradient(135deg, #4CAF50, #66BB6A);
      color: white;
      box-shadow: 0 8rpx 24rpx rgba(76, 175, 80, 0.3);
      
      &:active {
        transform: scale(0.98);
      }
    }
    
    &.download-btn {
      background: white;
      color: #1890ff;
      border: 2rpx solid #1890ff;
      
      &:active {
        background: #e6f7ff;
      }
    }
    
    &.view-btn {
      background: white;
      color: #52c41a;
      border: 2rpx solid #52c41a;
      
      &:active {
        background: #f6ffed;
      }
    }
  }
}

/* 弹窗样式 */
.popup-content {
  width: 600rpx;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  
  .popup-header {
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .popup-title {
      font-size: 36rpx;
      font-weight: 500;
      color: #333;
      text-align: center;
      display: block;
    }
  }
  
  .popup-body {
    padding: 40rpx 30rpx;
    
    .popup-text {
      display: block;
      font-size: 30rpx;
      color: #666;
      line-height: 1.8;
      margin-bottom: 20rpx;
    }
  }
  
  .popup-footer {
    padding: 0 30rpx 30rpx;
    display: flex;
    gap: 20rpx;
    
    .popup-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 32rpx;
      border: none;
      
      &.cancel {
        background: #f5f5f5;
        color: #666;
      }
      
      &.confirm {
        background: linear-gradient(135deg, #4CAF50, #66BB6A);
        color: white;
      }
    }
  }
}
</style>